//
//  LJRequestData.m
//  requestData
//
//  Created by MyMac on 15/8/7.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "LJRequestData.h"
#import "AFNetworking.h"
#import "XMLDictionary.h"
#import "NSString+Hashing.h"

@interface LJRequestData()<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@property(nonatomic,strong)NSURLConnection*connection;
@property(nonatomic,strong)NSMutableData*data;
@property(nonatomic,copy)DataCall datareceive;
@end
@implementation LJRequestData
+(void)afPostdataUrl:(NSString*)url andparam:(id)param finishedBlock:(void(^)(id complete))success failedBolck:(void(^)(id failed))failed
{
    AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/xml",@"application/json", nil];
//        [manager.requestSerializer setValue:@"x-requested-with" forHTTPHeaderField:@"XMLHttpRequest"];
//    [manager.requestSerializer setValue:@"*/*" forHTTPHeaderField:@"Accept"];
//    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36" forHTTPHeaderField:@"User-Agent"];
   // manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        XMLDictionaryParser*parser=[XMLDictionaryParser sharedInstance];
        NSDictionary*dict=[parser dictionaryWithString:operation.responseString];
        success(dict);
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failed(error.description);
    }];
    
}
+(void)afGETRequestUrl:(NSString*)url andFinishedBlock:(void(^)(id complete))success andfailedBlock:(void(^)(id failed))failed
{
    AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManager manager];
    
    
    
    
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        XMLDictionaryParser*parser=[XMLDictionaryParser sharedInstance];
        NSDictionary*dict=[parser dictionaryWithString:operation.responseString];
        success(dict);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failed(error.description);
    }];
   
}
+(NSURLResponse*)requestfileResponse:(NSString*)url;
{
    NSURLResponse*response=nil;
    NSError*error=nil;
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    return response;
}




+(void)requestDownDataUrl:(NSString*)url andfileName:(NSString*)name andfileType:(NSString*)type andfinishedBlock:(void(^)(id complete))success andfailed:(void(^)(id failed))failed
{
    
   
    NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString*doc=[NSString stringWithFormat:@"%@/Down",str];
    NSString*path=[NSString stringWithFormat:@"%@/Down/%@.%@",str,[url MD5Hash],type];
    [[NSFileManager defaultManager] createDirectoryAtPath:doc withIntermediateDirectories:YES attributes:nil error:nil];

    NSMutableURLRequest *request = [NSMutableURLRequest  requestWithURL:[NSURL URLWithString:url]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    
    
    //  NSString *range = [NSString stringWithFormat:@"Bytes=%d-",20000000];
    //  [request setValue:range forHTTPHeaderField:@"Range"];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        
        NSLog(@"%ld   %ld    %ld",(long)bytesRead,(long)totalBytesRead,(long)totalBytesExpectedToRead);
    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        BOOL ret=  [responseObject writeToFile:path atomically:YES];
        if(ret){
            
            
            success(path);
        }
        else{
            
            failed(@"下载失败");
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failed(error.localizedDescription);
        NSLog(@"%@",error);
    }];

    [operation start];
    
    
}
-(void)systemHTTPSRequest:(DataCall)data
{
    NSURL*httpsURL=[NSURL URLWithString:@"https://www.google.cn"];
    self.connection=[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:httpsURL] delegate:self];
    //self.datareceive=data;
   // [connection start];
}
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

{

 //获取trust object对象
    SecTrustRef trust=challenge.protectionSpace.serverTrust;
    SecTrustResultType result;
    //SecTrustEvaluate对trust进行验证
    OSStatus status=SecTrustEvaluate(trust, &result);
    if(status==errSecSuccess&&(result==kSecTrustResultProceed||result==kSecTrustResultUnspecified)){
    //验证成功，生成NSURLCredential凭证cred，告知challenge的sender使用这个凭证来继续链接
        NSURLCredential*cred=[NSURLCredential credentialForTrust:trust];
        [challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
    
    
    }else{
    //验证失败，取消这次验证流程
        [ challenge.sender cancelAuthenticationChallenge:challenge];
    
    
    
    }



}

//-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
//{
//
//    NSLog(@"%@",error.description);
//
//}
//-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
//{
//    self.data=[[NSMutableData alloc]init];
//
//    NSLog(@"%@",response);
//
//}
//-(void)connectionDidFinishLoading:(NSURLConnection *)connection
//{
//    //self.datareceive(self.data);
//    NSLog(@"完成");
//
//}
//-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
//{
//
//    [self.data appendData:data];
//
//
//}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] ==0){
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
    }else{
        [[challenge sender]cancelAuthenticationChallenge:challenge];
    }
}

-(void)dealloc
{

    NSLog(@"%@释放了",self.class);

}
@end
